<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class HealthEatController extends ApiController
{
    public function __construct()
    {
        parent::__construct();
        $user = Auth::user();
        if (empty($user->is_evaluate)) {
            return $this->failed("用户未参与评测");
        }
    }

    /**
     * 获取用户饮食记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $diary_id = $request->input("id", 0);
        $user = Auth::user();
        $user_id = $user->id;
        if (empty($diary_id)) {
            return $this->failed("参数错误");
        }
        $health_diary = DB::table('user_health_diary')->select('id', 'all_caloric', 'eat_caloric', 'sport_caloric', 'date')->where(['id' => $diary_id, 'user_id' => $user_id])->first();
        if(empty($health_diary)) {
            return $this->failed("参数错误");
        }

        $eat_record = DB::table('user_health_eat AS e')
            ->leftJoin('foods AS f', 'f.id', '=', 'e.food_id')
            ->select('e.id', 'e.type', 'e.count', 'e.caloric', 'f.name', 'f.unit')
            ->where(['e.diary_id' => $diary_id])
            ->get();
        $report = DB::table('user_health_report')->where(['user_id' => $user_id])->first();
        $suggest = ['min_morning' => round($report->min_caloric * 0.3), 'max_morning' => round($report->max_caloric * 0.3), 'min_nooning' => round($report->min_caloric * 0.4), 'max_nooning' => round($report->max_caloric * 0.4), 'min_evening' => round($report->min_caloric * 0.3), 'max_evening' => round($report->max_caloric * 0.3)];
        $eat_record = empty($eat_record) ? [] : $eat_record;
        return $this->success(['health_diary' => $health_diary, 'eat_record' => $eat_record, 'suggest_caloric' => $suggest]);
    }

    /**
     * 搜索食物
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchFood(Request $request)
    {
        $name = $request->input("name", "");
        $page = $request->input("page", 1);
        $where[] = ['status', '=', 1];
        if (!empty($name)) {
            $where[] = ['name', 'like', "%{$name}%"];
        }
        $limit = 10;
        $where = [['status', '=', 1], ['name', 'like', "%{$name}%"]];
        $count = DB::table('foods')->where($where)->count();
        $foods = DB::table('foods')->select('id', 'name', 'caloric', 'unit')->where($where)->skip($limit * ($page -1))->take($limit)->get();
        return $this->success(['foods' => $foods, 'more' => $count > $page * $limit ? true : false]);
    }


    /**
     * 添加食物
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addHealthEat(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $food_id = $request->input('food_id', 0);
        $diary_id = $request->input("diary_id", 0);
        $count = $request->input('count', 0);
        $type = $request->input('type', 0);
        if ($food_id <= 0) {
            return $this->failed("参数错误");
        }
        if ($diary_id <=0 ) {
            return $this->failed("参数错误");
        }
        if ($count <= 0) {
            return $this->failed("食物重量应大于0");
        }
        if (!in_array($type, array(1, 2, 3, 4, 5, 6))) {
            return $this->failed("参数错误");
        }
        $food = DB::table('foods')->where(['id' => $food_id, 'status' => 1])->first();
        if (empty($food)) {
            return $this->failed("该食物不存在");
        }
        $health_diary = DB::table('user_health_diary')->select('id', 'eat_caloric')->where(['id' => $diary_id, 'user_id' => $user_id])->first();
        if(empty($health_diary)) {
            return $this->failed("参数错误");
        }
        $caloric = round($count / 100 * $food->caloric);

        DB::beginTransaction(); //开启事务

        $food_is_add = DB::table('user_health_eat')->where(['diary_id' => $diary_id, "type" => $type, "food_id" => $food_id])->first(); //食物是否已添加（同天同餐）
        if (!empty($food_is_add)) {
            //已添加 则累加
            $eat_res = DB::table('user_health_eat')->where('id', $food_is_add->id)->update([
                'count' => $food_is_add->count + $count,
                'caloric' => $food_is_add->caloric + $caloric,
                'fat_caloric' => $food_is_add->fat_caloric + round($count / 100 * $food->fat_caloric),
                'protein_caloric' => $food_is_add->protein_caloric + round($count / 100 * $food->protein_caloric),
                'carbohydrate_caloric' => $food_is_add->carbohydrate_caloric + round($count / 100 * $food->carbohydrate_caloric)
            ]);
        } else {
            $eat_res = DB::table('user_health_eat')->insert([
                'user_id' => $user_id,
                'food_id' => $food_id,
                'diary_id' => $diary_id,
                'type' => $type,
                'count' => $count,
                'caloric' => $caloric,
                'fat_caloric' => round($count / 100 * $food->fat_caloric),
                'protein_caloric' => round($count / 100 * $food->protein_caloric),
                'carbohydrate_caloric' => round($count / 100 * $food->carbohydrate_caloric)

            ]);
        }

        $diary_res = DB::table('user_health_diary')->where('id', $diary_id)->increment('eat_caloric', $caloric);

        if (empty($eat_res) || empty($diary_res)) {
            DB::rollBack(); //回滚事务
            return $this->failed("添加失败");
        }
        DB::commit(); //提交事务
        return $this->success("添加成功");
    }

    /**
     * 修改饮食数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editHealthEat(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $eat_id = $request->input('eat_id', 0);
        $count = $request->input('count', 0);

        if ($eat_id <= 0) {
            return $this->failed("参数错误");
        }
        if ($count <= 0) {
            return $this->failed("食物重量应大于0");
        }

        $health_eat = DB::table('user_health_eat')->where(['id' => $eat_id, 'user_id' => $user_id])->first();
        if (empty($health_eat)) {
            return $this->failed("该记录不存在");
        }

        $health_diary = DB::table('user_health_diary')->select('id', 'eat_caloric')->where(['id' => $health_eat->diary_id])->first();
        if(empty($health_diary)) {
            $this->failed("参数错误");
        }

        $food = DB::table('foods')->where(['id' => $health_eat->food_id, 'status' => 1])->first();
        if (empty($food)) {
            return $this->failed("该食物已不存在，无法修改");
        }

        $caloric = round($count / 100 * $food->caloric);
        $eat_caloric = $health_diary->eat_caloric + $caloric - $health_eat->caloric;
        if ($eat_caloric <= 0) {
            $eat_caloric = 0;
        }

        DB::beginTransaction(); //开启事务

        $eat_res = DB::table('user_health_eat')->where('id', $eat_id)->update([
            'count' => $count,
            'caloric' => $caloric,
            'fat_caloric' => round($count / 100 * $food->fat_caloric),
            'protein_caloric' => round($count / 100 * $food->protein_caloric),
            'carbohydrate_caloric' => round($count / 100 * $food->carbohydrate_caloric)

        ]);
        $diary_res = DB::table('user_health_diary')->where('id', $health_eat->diary_id)->update(['eat_caloric' => $eat_caloric]);

        if ($eat_res === false || $diary_res === false) {
            DB::rollBack(); //回滚事务
            return $this->failed("修改失败");
        }
        DB::commit(); //提交事务
        return $this->success("修改成功");
    }

    /**
     * 删除数据
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteHealthEat(Request $request)
    {
        $user = Auth::user();
        $user_id = $user->id;
        $eat_id = $request->input('eat_id', 0);

        if ($eat_id <= 0) {
            return $this->failed("参数错误");
        }

        $health_eat = DB::table('user_health_eat')->where(['id' => $eat_id, 'user_id' => $user_id])->first();
        if (empty($health_eat)) {
            return $this->failed("该记录不存在");
        }

        $health_diary = DB::table('user_health_diary')->select('id', 'eat_caloric')->where(['id' => $health_eat->diary_id])->first();
        if(empty($health_diary)) {
            $this->failed("参数错误");
        }

        $food = DB::table('foods')->where(['id' => $health_eat->food_id, 'status' => 1])->first();
        if (empty($food)) {
            return $this->failed("该食物已不存在，无法修改");
        }

        $eat_caloric = $health_diary->eat_caloric - $health_eat->caloric;
        if ($eat_caloric <= 0) {
            $eat_caloric = 0;
        }

        DB::beginTransaction(); //开启事务
        $eat_res = DB::table('user_health_eat')->where('id', $eat_id)->delete();
        $diary_res = DB::table('user_health_diary')->where('id', $health_eat->diary_id)->update(['eat_caloric' => $eat_caloric]);

        if (empty($eat_res) || empty($diary_res)) {
            DB::rollBack(); //回滚事务
            return $this->failed("删除失败");
        }
        DB::commit(); //提交事务
        return $this->success("删除成功");
    }
}
